package com.tron.thread.singleThread;

public class Gate {
    public Boolean isOpen = true;
    public Integer count = 0;
    private String name;
    private String address;

    public void pass(String name, String address) {
        // --- 需要获取锁
        this.count++;
        /**
         * 异常复现
         * a线程获取操作权限，设置名称为aName
         */
        this.name = name;
        /**
         * b线程获取操作权，设置名称bName，设置地址bAddress
         */
        /**
         * a线程获取线程操作权限，设置地址aAddress，此时name -> bName  address -> aAddress
         */
        this.address = address;

        check();
        // --- 释放锁
    }

    public String toString() {
        // --- 获取锁
        return  count +" : "+ name + " : " + address;
        // --- 释放锁
    }

    private void check() {
        if (this.name.charAt(0) != address.charAt(0)) {
            /**
             * 如果此时比较的结果不相等，但是toString方法获取name和address的时候，值一样会被其他线程修改
             */
            System.out.println("===================发现异常数据："+toString());
            closeGate();
        }
    }

    private void closeGate() {
        this.isOpen = false;
    }
}
